import React, { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { 
  Card, 
  Spin, 
  Alert, 
  Button, 
  Row, 
  Col, 
  Input,
  Select,
  Tag,
  Space,
  Typography,
  Divider
} from 'antd';
import { 
  FaSync,
  FaSearch,
  FaFilter,
  FaDownload,
  FaCopy,
  FaTrash
} from 'react-icons/fa';
import { useAuthStore } from '../../../stores/authStore';
import { useThemeStore } from '../../../stores/themeStore';
import { getTheme } from '../../../theme/config';
import CustomTable from '../../../components/custom/CustomTable';

const { Title, Text } = Typography;
const { Option } = Select;

interface LogEntry {
  id: string;
  timestamp: string;
  level: 'info' | 'warn' | 'error' | 'debug';
  message: string;
  taskId?: string;
  spider?: string;
}

const CrawlerLogsPage: React.FC = () => {
  const navigate = useNavigate();
  const { isAuthenticated } = useAuthStore();
  const { mode } = useThemeStore();
  const theme = getTheme(mode);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const [logs, setLogs] = useState<LogEntry[]>([]);
  const [filteredLogs, setFilteredLogs] = useState<LogEntry[]>([]);
  const [searchText, setSearchText] = useState('');
  const [levelFilter, setLevelFilter] = useState<string>('all');
  const [taskFilter, setTaskFilter] = useState<string>('all');
  const logContainerRef = useRef<HTMLDivElement>(null);

  // 检查认证状态
  useEffect(() => {
    if (!isAuthenticated) {
      navigate('/login');
    }
  }, [navigate]); // 移除isAuthenticated依赖以避免无限循环

  // 模拟获取日志数据
  useEffect(() => {
    const fetchData = async () => {
      try {
        setLoading(true);
        setError(null);
        
        // 模拟日志数据
        const mockLogs: LogEntry[] = [
          {
            id: '1',
            timestamp: '2023-12-01 14:30:22',
            level: 'info',
            message: '爬虫任务 "电商商品爬虫" 开始执行',
            taskId: 'task_001',
            spider: 'product_spider'
          },
          {
            id: '2',
            timestamp: '2023-12-01 14:30:25',
            level: 'info',
            message: '连接到目标网站: https://example-shop.com',
            taskId: 'task_001',
            spider: 'product_spider'
          },
          {
            id: '3',
            timestamp: '2023-12-01 14:30:30',
            level: 'debug',
            message: '发送HTTP请求: GET /products?page=1',
            taskId: 'task_001',
            spider: 'product_spider'
          },
          {
            id: '4',
            timestamp: '2023-12-01 14:30:35',
            level: 'info',
            message: '成功获取页面数据，共25条商品信息',
            taskId: 'task_001',
            spider: 'product_spider'
          },
          {
            id: '5',
            timestamp: '2023-12-01 14:30:40',
            level: 'warn',
            message: '部分字段解析失败，使用默认值',
            taskId: 'task_001',
            spider: 'product_spider'
          },
          {
            id: '6',
            timestamp: '2023-12-01 14:30:45',
            level: 'error',
            message: '网络连接超时，重试第1次',
            taskId: 'task_001',
            spider: 'product_spider'
          },
          {
            id: '7',
            timestamp: '2023-12-01 14:30:50',
            level: 'info',
            message: '重新连接成功，继续执行任务',
            taskId: 'task_001',
            spider: 'product_spider'
          },
          {
            id: '8',
            timestamp: '2023-12-01 12:15:45',
            level: 'info',
            message: '爬虫任务 "新闻文章爬虫" 开始执行',
            taskId: 'task_002',
            spider: 'article_spider'
          },
          {
            id: '9',
            timestamp: '2023-12-01 12:20:15',
            level: 'info',
            message: '成功爬取文章数据，共156条记录',
            taskId: 'task_002',
            spider: 'article_spider'
          },
          {
            id: '10',
            timestamp: '2023-12-01 12:25:30',
            level: 'info',
            message: '爬虫任务 "新闻文章爬虫" 执行完成',
            taskId: 'task_002',
            spider: 'article_spider'
          }
        ];
        
        setLogs(mockLogs);
        setFilteredLogs(mockLogs);
      } catch (err) {
        console.error('获取日志数据失败:', err);
        setError('获取日志数据失败: ' + (err instanceof Error ? err.message : '未知错误'));
      } finally {
        setLoading(false);
      }
    };

    if (isAuthenticated) {
      fetchData();
    }
  }, []); // 空依赖数组确保只在组件挂载时执行一次

  // 过滤日志
  useEffect(() => {
    let result = logs;
    
    // 按搜索文本过滤
    if (searchText) {
      result = result.filter(log => 
        log.message.toLowerCase().includes(searchText.toLowerCase()) ||
        (log.spider && log.spider.toLowerCase().includes(searchText.toLowerCase())) ||
        (log.taskId && log.taskId.toLowerCase().includes(searchText.toLowerCase()))
      );
    }
    
    // 按日志级别过滤
    if (levelFilter !== 'all') {
      result = result.filter(log => log.level === levelFilter);
    }
    
    // 按任务过滤
    if (taskFilter !== 'all') {
      result = result.filter(log => log.taskId === taskFilter);
    }
    
    setFilteredLogs(result);
  }, [searchText, levelFilter, taskFilter, logs]);

  // 刷新日志
  const refreshLogs = async () => {
    try {
      setLoading(true);
      // 模拟刷新
      await new Promise(resolve => setTimeout(resolve, 1000));
    } catch (err) {
      setError('刷新失败: ' + (err instanceof Error ? err.message : '未知错误'));
    } finally {
      setLoading(false);
    }
  };

  // 获取日志级别颜色
  const getLevelColor = (level: string) => {
    switch (level) {
      case 'info':
        return 'blue';
      case 'warn':
        return 'orange';
      case 'error':
        return 'red';
      case 'debug':
        return 'purple';
      default:
        return 'default';
    }
  };

  // 获取日志级别标签
  const getLevelLabel = (level: string) => {
    switch (level) {
      case 'info':
        return '信息';
      case 'warn':
        return '警告';
      case 'error':
        return '错误';
      case 'debug':
        return '调试';
      default:
        return level;
    }
  };

  // 复制日志
  const copyLogs = () => {
    const logText = filteredLogs.map(log => 
      `[${log.timestamp}] [${log.level.toUpperCase()}] ${log.message}`
    ).join('\n');
    
    navigator.clipboard.writeText(logText);
    // message.success('日志已复制到剪贴板');
  };

  // 下载日志
  const downloadLogs = () => {
    const logText = filteredLogs.map(log => 
      `[${log.timestamp}] [${log.level.toUpperCase()}] ${log.message}`
    ).join('\n');
    
    const blob = new Blob([logText], { type: 'text/plain' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `crawler-logs-${new Date().toISOString().slice(0, 10)}.txt`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
  };

  // 清空日志
  const clearLogs = () => {
    setLogs([]);
    setFilteredLogs([]);
  };

  // 获取唯一的任务ID列表
  const uniqueTaskIds = Array.from(new Set(logs.map(log => log.taskId).filter(Boolean))) as string[];

  // 获取卡片样式
  const getCardStyle = () => ({
    background: theme.cardBackground,
    border: `1px solid ${theme.cardBorder}`,
    borderRadius: '12px',
    boxShadow: mode === 'light' ? theme.cardShadow : 'none'
  });

  // 日志表格列定义
  const columns = [
    {
      title: '时间',
      dataIndex: 'timestamp',
      key: 'timestamp',
      render: (text: string) => <span style={{ color: theme.textPrimary }}>{text}</span>
    },
    {
      title: '级别',
      dataIndex: 'level',
      key: 'level',
      render: (level: string) => (
        <Tag color={getLevelColor(level)}>
          {getLevelLabel(level)}
        </Tag>
      )
    },
    {
      title: '任务ID',
      dataIndex: 'taskId',
      key: 'taskId',
      render: (taskId: string) => taskId ? (
        <Tag color="blue">{taskId}</Tag>
      ) : (
        <span style={{ color: theme.textSecondary }}>-</span>
      )
    },
    {
      title: '爬虫',
      dataIndex: 'spider',
      key: 'spider',
      render: (spider: string) => spider ? (
        <Tag color="green">{spider}</Tag>
      ) : (
        <span style={{ color: theme.textSecondary }}>-</span>
      )
    },
    {
      title: '消息',
      dataIndex: 'message',
      key: 'message',
      render: (message: string, record: LogEntry) => (
        <Text 
          style={{ 
            color: record.level === 'error' ? '#ff4d4f' : 
                   record.level === 'warn' ? '#faad14' : 
                   record.level === 'info' ? '#1890ff' : 
                   '#b37feb'
          }}
        >
          {message}
        </Text>
      )
    }
  ];

  if (!isAuthenticated) {
    return null;
  }

  return (
    <div style={{ padding: '24px', color: theme.textPrimary }}>
      <div style={{ marginBottom: '24px' }}>
        <h1 style={{ 
          color: theme.glowColor, 
          fontSize: '28px',
          fontWeight: 'bold',
          marginBottom: '8px'
        }}>
          爬虫日志查看
        </h1>
        <p style={{ 
          fontSize: '16px',
          opacity: 0.8,
          marginBottom: '24px',
          color: theme.textSecondary
        }}>
          查看和分析爬虫任务执行日志
        </p>
      </div>

      {/* 操作栏 */}
      <div style={{ 
        marginBottom: '24px',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        flexWrap: 'wrap',
        gap: '12px'
      }}>
        <div>
          <Button 
            icon={<FaSync />}
            onClick={refreshLogs}
            style={{ 
              background: theme.cardBackground,
              border: `1px solid ${theme.cardBorder}`,
              color: theme.textPrimary
            }}
          >
            刷新
          </Button>
          <Button 
            style={{ 
              marginLeft: '12px',
              background: theme.cardBackground,
              border: `1px solid ${theme.cardBorder}`,
              color: theme.textPrimary
            }}
            icon={<FaCopy />}
            onClick={copyLogs}
          >
            复制
          </Button>
          <Button 
            style={{ 
              marginLeft: '12px',
              background: theme.cardBackground,
              border: `1px solid ${theme.cardBorder}`,
              color: theme.textPrimary
            }}
            icon={<FaDownload />}
            onClick={downloadLogs}
          >
            下载
          </Button>
          <Button 
            danger
            style={{ marginLeft: '12px' }}
            icon={<FaTrash />}
            onClick={clearLogs}
          >
            清空
          </Button>
        </div>
        
        <div style={{ display: 'flex', gap: '12px' }}>
          <Input 
            placeholder="搜索日志..."
            prefix={<FaSearch style={{ color: theme.textSecondary }} />}
            style={{ 
              width: '200px',
              background: theme.cardBackground,
              border: `1px solid ${theme.cardBorder}`,
              color: theme.textPrimary
            }}
            value={searchText}
            onChange={(e) => setSearchText(e.target.value)}
          />
          <Select 
            placeholder="日志级别"
            style={{ 
              width: '120px',
              background: theme.cardBackground,
              border: `1px solid ${theme.cardBorder}`,
              color: theme.textPrimary
            }}
            value={levelFilter}
            onChange={setLevelFilter}
            dropdownStyle={{ 
              background: theme.cardBackground,
              border: `1px solid ${theme.cardBorder}`
            }}
          >
            <Option value="all">全部级别</Option>
            <Option value="info">信息</Option>
            <Option value="warn">警告</Option>
            <Option value="error">错误</Option>
            <Option value="debug">调试</Option>
          </Select>
          <Select 
            placeholder="任务筛选"
            style={{ 
              width: '150px',
              background: theme.cardBackground,
              border: `1px solid ${theme.cardBorder}`,
              color: theme.textPrimary
            }}
            value={taskFilter}
            onChange={setTaskFilter}
            dropdownStyle={{ 
              background: theme.cardBackground,
              border: `1px solid ${theme.cardBorder}`
            }}
          >
            <Option value="all">全部任务</Option>
            {uniqueTaskIds.map(taskId => (
              <Option 
                key={taskId} 
                value={taskId}
                style={{ color: theme.textPrimary }}
              >
                {taskId}
              </Option>
            ))}
          </Select>
          <Button 
            icon={<FaFilter />}
            style={{ 
              background: theme.cardBackground,
              border: `1px solid ${theme.cardBorder}`,
              color: theme.textPrimary
            }}
          >
            筛选
          </Button>
        </div>
      </div>

      {/* 日志统计 */}
      <Row gutter={[24, 24]} style={{ marginBottom: '24px' }}>
        <Col xs={24} sm={6}>
          <Card 
            style={getCardStyle()}
            bodyStyle={{ padding: '16px' }}
          >
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ 
                background: mode === 'dark' ? 'rgba(24, 144, 255, 0.2)' : 'rgba(24, 144, 255, 0.1)',
                borderRadius: '50%',
                width: '40px',
                height: '40px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                marginRight: '12px'
              }}>
                <FaSearch style={{ color: '#1890ff', fontSize: '18px' }} />
              </div>
              <div>
                <div style={{ fontSize: '14px', opacity: 0.8, color: theme.textSecondary }}>总日志数</div>
                <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#1890ff' }}>
                  {logs.length}
                </div>
              </div>
            </div>
          </Card>
        </Col>

        <Col xs={24} sm={6}>
          <Card 
            style={getCardStyle()}
            bodyStyle={{ padding: '16px' }}
          >
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ 
                background: mode === 'dark' ? 'rgba(255, 77, 79, 0.2)' : 'rgba(255, 77, 79, 0.1)',
                borderRadius: '50%',
                width: '40px',
                height: '40px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                marginRight: '12px'
              }}>
                <FaSearch style={{ color: '#ff4d4f', fontSize: '18px' }} />
              </div>
              <div>
                <div style={{ fontSize: '14px', opacity: 0.8, color: theme.textSecondary }}>错误数</div>
                <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#ff4d4f' }}>
                  {logs.filter(log => log.level === 'error').length}
                </div>
              </div>
            </div>
          </Card>
        </Col>

        <Col xs={24} sm={6}>
          <Card 
            style={getCardStyle()}
            bodyStyle={{ padding: '16px' }}
          >
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ 
                background: mode === 'dark' ? 'rgba(250, 173, 20, 0.2)' : 'rgba(250, 173, 20, 0.1)',
                borderRadius: '50%',
                width: '40px',
                height: '40px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                marginRight: '12px'
              }}>
                <FaSearch style={{ color: '#faad14', fontSize: '18px' }} />
              </div>
              <div>
                <div style={{ fontSize: '14px', opacity: 0.8, color: theme.textSecondary }}>警告数</div>
                <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#faad14' }}>
                  {logs.filter(log => log.level === 'warn').length}
                </div>
              </div>
            </div>
          </Card>
        </Col>

        <Col xs={24} sm={6}>
          <Card 
            style={getCardStyle()}
            bodyStyle={{ padding: '16px' }}
          >
            <div style={{ display: 'flex', alignItems: 'center' }}>
              <div style={{ 
                background: mode === 'dark' ? 'rgba(97, 220, 163, 0.2)' : 'rgba(97, 220, 163, 0.1)',
                borderRadius: '50%',
                width: '40px',
                height: '40px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
                marginRight: '12px'
              }}>
                <FaSearch style={{ color: '#61dca3', fontSize: '18px' }} />
              </div>
              <div>
                <div style={{ fontSize: '14px', opacity: 0.8, color: theme.textSecondary }}>任务数</div>
                <div style={{ fontSize: '18px', fontWeight: 'bold', color: '#61dca3' }}>
                  {uniqueTaskIds.length}
                </div>
              </div>
            </div>
          </Card>
        </Col>
      </Row>

      {/* 日志内容 */}
      <Card 
        style={getCardStyle()}
      >
        {error ? (
          <Alert
            message="错误"
            description={error}
            type="error"
            showIcon
            style={{ 
              marginBottom: '16px',
              background: theme.cardBackground,
              border: `1px solid ${theme.cardBorder}`
            }}
          />
        ) : null}
        
        {loading ? (
          <div style={{ textAlign: 'center', padding: '40px' }}>
            <Spin size="large" tip="加载中..." />
          </div>
        ) : (
          <CustomTable 
            dataSource={filteredLogs}
            columns={columns}
            rowKey="id"
            pagination={{
              pageSize: 10,
              showSizeChanger: true,
              showQuickJumper: true,
              style: {
                background: theme.cardBackground,
                color: theme.textPrimary,
                borderTop: `1px solid ${theme.cardBorder}`
              }
            }}
            locale={{
              emptyText: (
                <div style={{ padding: '40px', textAlign: 'center', color: theme.textSecondary }}>
                  <FaSearch style={{ fontSize: '48px', marginBottom: '16px', opacity: 0.5, color: theme.glowColor }} />
                  <p>暂无匹配的日志记录</p>
                </div>
              )
            }}
          />
        )}
      </Card>
    </div>
  );
};

export default CrawlerLogsPage;